package ru.paswd.marketprice.ui.presenter

import moxy.InjectViewState
import ru.paswd.marketprice.Application
import ru.paswd.marketprice.data.mappers.PriceMapper
import ru.paswd.marketprice.data.mappers.PriceWithShopMapper
import ru.paswd.marketprice.data.models.LatLng
import ru.paswd.marketprice.data.models.Price
import ru.paswd.marketprice.data.models.PriceWithShop
import ru.paswd.marketprice.data.repositories.PriceHistoryRepository
import ru.paswd.marketprice.data.repositories.PricesRepository
import ru.paswd.marketprice.ui.view.PriceMapView
import java.util.*
import java.util.stream.Collectors

@InjectViewState
class PriceMapPresenter : BasePresenter<PriceMapView>() {
    fun updateMap(productId: UUID, radiusMeters: Int?, lat: Double, lng: Double) {
        PricesRepository.requestAll(Application.instance!!.applicationContext!!,
                productId, radiusMeters, lat, lng, false
        ) { success, result ->
            if (success) {
                viewState?.setMapPoints(
                        LatLng(lat, lng),
                        result?.stream()
                                ?.map { PriceWithShopMapper.fromDto(it) }
                                ?.collect(Collectors.toList())
                                ?: listOf()
                )
            }
            viewState?.onRefreshed()
        }
    }

    fun onShopClicked(priceWithShop: PriceWithShop) {
        viewState?.displayShopInfo(priceWithShop)
    }

    fun getPriceHistory(productId: UUID, shopId: UUID) {
        PriceHistoryRepository.requestAll(Application.instance!!.applicationContext!!,
            productId, shopId) { success, result ->
            var history = listOf<Price>()
            if (success) {
                history = result.stream()
                    .map { p -> PriceMapper.fromDto(p) }
                    .collect(Collectors.toList())
            }

            viewState?.displayHistory(history)
        }
    }
}